<template>
  <div class="app-container">
    <div class="search-container">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item>
          <el-button type="primary" @click="handleQuery">
            <template #icon><Search /></template>
            搜索
          </el-button>
          <el-button @click="handleResetQuery">
            <template #icon><Refresh /></template>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never">
      <div class="mb-10px">
        <el-button v-hasPerm="['factory:users:add']" type="success" @click="handleOpenDialog()">
          <template #icon><Plus /></template>
          新增
        </el-button>
        <el-button
          v-hasPerm="['factory:users:delete']"
          type="danger"
          :disabled="removeIds.length === 0"
          @click="handleDelete()"
        >
          <template #icon><Delete /></template>
          删除
        </el-button>
      </div>

      <el-table
        ref="dataTableRef"
        v-loading="loading"
        :data="pageData"
        highlight-current-row
        border
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column key="userId" label="" prop="userId" min-width="150" align="center" />
        <el-table-column
          key="factoryId"
          label="所属服装厂ID，关联到工厂表"
          prop="factoryId"
          min-width="150"
          align="center"
        />
        <el-table-column
          key="username"
          label="用户名，用于登录"
          prop="username"
          min-width="150"
          align="center"
        />
        <el-table-column
          key="passwordHash"
          label="加密后的密码"
          prop="passwordHash"
          min-width="150"
          align="center"
        />
        <el-table-column
          key="realName"
          label="真实姓名"
          prop="realName"
          min-width="150"
          align="center"
        />
        <el-table-column key="phone" label="联系电话" prop="phone" min-width="150" align="center" />
        <el-table-column key="email" label="电子邮箱" prop="email" min-width="150" align="center" />
        <el-table-column
          key="role"
          label="用户角色：worker-普通员工, supervisor-组长/主管, manager-厂长, admin-系统管理员"
          prop="role"
          min-width="150"
          align="center"
        />
        <el-table-column
          key="department"
          label="所属部门，如裁剪部、缝制部、包装部等"
          prop="department"
          min-width="150"
          align="center"
        />
        <el-table-column
          key="position"
          label="职位"
          prop="position"
          min-width="150"
          align="center"
        />
        <el-table-column
          key="hireDate"
          label="入职日期"
          prop="hireDate"
          min-width="150"
          align="center"
        />
        <el-table-column
          key="status"
          label="账号状态：0-禁用，1-启用"
          prop="status"
          min-width="150"
          align="center"
        />
        <el-table-column
          key="loginIpAddress"
          label="登录时ip所在地"
          prop="loginIpAddress"
          min-width="150"
          align="center"
        />
        <el-table-column
          key="loginIp"
          label="登录时ip "
          prop="loginIp"
          min-width="150"
          align="center"
        />
        <el-table-column
          key="lastLogin"
          label="最后登录时间"
          prop="lastLogin"
          min-width="150"
          align="center"
        />
        <el-table-column
          key="createdAt"
          label="创建时间"
          prop="createdAt"
          min-width="150"
          align="center"
        />
        <el-table-column
          key="updatedAt"
          label="更新时间"
          prop="updatedAt"
          min-width="150"
          align="center"
        />
        <el-table-column
          key="createdBy"
          label="创建人ID"
          prop="createdBy"
          min-width="150"
          align="center"
        />
        <el-table-column key="notes" label="备注信息" prop="notes" min-width="150" align="center" />
        <el-table-column fixed="right" label="操作" width="220">
          <template #default="scope">
            <el-button
              v-hasPerm="['factory:users:edit']"
              type="primary"
              size="small"
              link
              @click="handleOpenDialog(scope.row.id)"
            >
              <template #icon><Edit /></template>
              编辑
            </el-button>
            <el-button
              v-hasPerm="['factory:users:delete']"
              type="danger"
              size="small"
              link
              @click="handleDelete(scope.row.id)"
            >
              <template #icon><Delete /></template>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-if="total > 0"
        v-model:total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="handleQuery()"
      />
    </el-card>

    <!-- 服装厂用户表单弹窗 -->
    <el-dialog
      v-model="dialog.visible"
      :title="dialog.title"
      width="500px"
      @close="handleCloseDialog"
    >
      <el-form ref="dataFormRef" :model="formData" :rules="rules" label-width="100px">
        <el-form-item label="" prop="userId">
          <el-input v-model="formData.userId" placeholder="" />
        </el-form-item>

        <el-form-item label="所属服装厂ID，关联到工厂表" prop="factoryId">
          <el-input v-model="formData.factoryId" placeholder="所属服装厂ID，关联到工厂表" />
        </el-form-item>

        <el-form-item label="用户名，用于登录" prop="username">
          <el-input v-model="formData.username" placeholder="用户名，用于登录" />
        </el-form-item>

        <el-form-item label="加密后的密码" prop="passwordHash">
          <el-input v-model="formData.passwordHash" placeholder="加密后的密码" />
        </el-form-item>

        <el-form-item label="真实姓名" prop="realName">
          <el-input v-model="formData.realName" placeholder="真实姓名" />
        </el-form-item>

        <el-form-item label="联系电话" prop="phone">
          <el-input v-model="formData.phone" placeholder="联系电话" />
        </el-form-item>

        <el-form-item label="电子邮箱" prop="email">
          <el-input v-model="formData.email" placeholder="电子邮箱" />
        </el-form-item>

        <el-form-item
          label="用户角色：worker-普通员工, supervisor-组长/主管, manager-厂长, admin-系统管理员"
          prop="role"
        >
          <el-input
            v-model="formData.role"
            placeholder="用户角色：worker-普通员工, supervisor-组长/主管, manager-厂长, admin-系统管理员"
          />
        </el-form-item>

        <el-form-item label="所属部门，如裁剪部、缝制部、包装部等" prop="department">
          <el-input
            v-model="formData.department"
            placeholder="所属部门，如裁剪部、缝制部、包装部等"
          />
        </el-form-item>

        <el-form-item label="职位" prop="position">
          <el-input v-model="formData.position" placeholder="职位" />
        </el-form-item>

        <el-form-item label="入职日期" prop="hireDate">
          <el-date-picker
            v-model="formData.hireDate"
            class="!w-[240px]"
            type="date"
            placeholder="入职日期"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>

        <el-form-item label="账号状态：0-禁用，1-启用" prop="status">
          <el-input v-model="formData.status" placeholder="账号状态：0-禁用，1-启用" />
        </el-form-item>

        <el-form-item label="登录时ip所在地" prop="loginIpAddress">
          <el-input v-model="formData.loginIpAddress" placeholder="登录时ip所在地" />
        </el-form-item>

        <el-form-item label="登录时ip " prop="loginIp">
          <el-input v-model="formData.loginIp" placeholder="登录时ip " />
        </el-form-item>

        <el-form-item label="最后登录时间" prop="lastLogin">
          <el-date-picker
            v-model="formData.lastLogin"
            type="datetime"
            placeholder="最后登录时间"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>

        <el-form-item label="创建时间" prop="createdAt">
          <el-date-picker
            v-model="formData.createdAt"
            type="datetime"
            placeholder="创建时间"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>

        <el-form-item label="更新时间" prop="updatedAt">
          <el-date-picker
            v-model="formData.updatedAt"
            type="datetime"
            placeholder="更新时间"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>

        <el-form-item label="创建人ID" prop="createdBy">
          <el-input v-model="formData.createdBy" placeholder="创建人ID" />
        </el-form-item>

        <el-form-item label="备注信息" prop="notes">
          <el-input v-model="formData.notes" placeholder="备注信息" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit()">确定</el-button>
          <el-button @click="handleCloseDialog()">取消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
defineOptions({
  name: "Users",
  inheritAttrs: false,
});

import UsersAPI, { UsersPageVO, UsersForm, UsersPageQuery } from "@/api/factory/users";

const queryFormRef = ref();
const dataFormRef = ref();

const loading = ref(false);
const removeIds = ref<number[]>([]);
const total = ref(0);

const queryParams = reactive<UsersPageQuery>({
  pageNum: 1,
  pageSize: 10,
});

// 服装厂用户表格数据
const pageData = ref<UsersPageVO[]>([]);

// 弹窗
const dialog = reactive({
  title: "",
  visible: false,
});

// 服装厂用户表单数据
const formData = reactive<UsersForm>({});

// 服装厂用户表单校验规则
const rules = reactive({
  userId: [{ required: true, message: "请输入", trigger: "blur" }],
  factoryId: [{ required: true, message: "请输入所属服装厂ID，关联到工厂表", trigger: "blur" }],
  username: [{ required: true, message: "请输入用户名，用于登录", trigger: "blur" }],
  passwordHash: [{ required: true, message: "请输入加密后的密码", trigger: "blur" }],
  realName: [{ required: true, message: "请输入真实姓名", trigger: "blur" }],
  role: [
    {
      required: true,
      message:
        "请输入用户角色：worker-普通员工, supervisor-组长/主管, manager-厂长, admin-系统管理员",
      trigger: "blur",
    },
  ],
});

/** 查询服装厂用户 */
function handleQuery() {
  loading.value = true;
  UsersAPI.getPage(queryParams)
    .then((data) => {
      pageData.value = data.list;
      total.value = data.total;
    })
    .finally(() => {
      loading.value = false;
    });
}

/** 重置服装厂用户查询 */
function handleResetQuery() {
  queryFormRef.value!.resetFields();
  queryParams.pageNum = 1;
  handleQuery();
}

/** 行复选框选中记录选中ID集合 */
function handleSelectionChange(selection: any) {
  removeIds.value = selection.map((item: any) => item.id);
}

/** 打开服装厂用户弹窗 */
function handleOpenDialog(id?: number) {
  dialog.visible = true;
  if (id) {
    dialog.title = "修改服装厂用户";
    UsersAPI.getFormData(id).then((data) => {
      Object.assign(formData, data);
    });
  } else {
    dialog.title = "新增服装厂用户";
  }
}

/** 提交服装厂用户表单 */
function handleSubmit() {
  dataFormRef.value.validate((valid: any) => {
    if (valid) {
      loading.value = true;
      const id = formData.id;
      if (id) {
        UsersAPI.update(id, formData)
          .then(() => {
            ElMessage.success("修改成功");
            handleCloseDialog();
            handleResetQuery();
          })
          .finally(() => (loading.value = false));
      } else {
        UsersAPI.add(formData)
          .then(() => {
            ElMessage.success("新增成功");
            handleCloseDialog();
            handleResetQuery();
          })
          .finally(() => (loading.value = false));
      }
    }
  });
}

/** 关闭服装厂用户弹窗 */
function handleCloseDialog() {
  dialog.visible = false;
  dataFormRef.value.resetFields();
  dataFormRef.value.clearValidate();
  formData.id = undefined;
}

/** 删除服装厂用户 */
function handleDelete(id?: number) {
  const ids = [id || removeIds.value].join(",");
  if (!ids) {
    ElMessage.warning("请勾选删除项");
    return;
  }

  ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(
    () => {
      loading.value = true;
      UsersAPI.deleteByIds(ids)
        .then(() => {
          ElMessage.success("删除成功");
          handleResetQuery();
        })
        .finally(() => (loading.value = false));
    },
    () => {
      ElMessage.info("已取消删除");
    }
  );
}

onMounted(() => {
  handleQuery();
});
</script>
